#! /usr/bin/env lua
--
-- update-protocol-ids
-- Copyright (C) 2016-2017 Adrian Perez <aperez@igalia.com>
--
-- Distributed under terms of the Apache License 2.0.
--

if #arg ~= 0 then
	io.stderr:write("Usage: update-protocol-ids < path/to/ndpi_protocol_ids.h\n")
	os.exit(1)
end

--
-- Parse the input header
--
local define_pattern = "^%#define%s+NDPI_([^%s]+)%s+([%a%d_]+)"
local ref_pattern = "^NDPI_([%a%d_]+)$"

local items = {}
local references = {}

for line in io.lines() do
	local name, value = line:match(define_pattern)
	if name and value and name ~= "LAST_IMPLEMENTED_PROTOCOL" then
		local ref_name = value:match(ref_pattern)
		if ref_name then
			table.insert(references, { name = name, value = ref_name })
      else
         table.insert(items, { name = name, value = tonumber(value) })
		end
	end
end
table.sort(items, function (a, b) return a.value < b.value end)

--
-- Generate Lua module
--
print("-- Generated by ljdnpi's tools/update-protocol-ids script")
print("local T = {")
for _, item in ipairs(items) do
   print("  [" .. item.value .. "] = \"" .. item.name .. "\",")
end
for _, item in ipairs(items) do
   print("  " .. item.name .. " = " .. item.value .. ",")
end
print("}")

for _, item in ipairs(references) do
   print("T." .. item.name .. " = T." .. item.value)
end

print("return T")
